package com.imflea.zero.service.meeting.impl;

import com.imflea.zero.service.meeting.IMeetingOrderInfoService;
import com.imflea.zero.task.TimeOutTaskHandleTask;
import com.imflea.zero.utils.TaskTimeOutUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Set;

/**
 * @author 祥保玉
 * @version 1.0
 * @project farmplus-service
 * @package com.imflea.zero.service.mall.impl
 * @filename 创建时间: 2022/1/4
 * @description
 * @copyright Copyright (c) 2021 中国软件与技术服务股份有限公司
 */
@Component
@Slf4j
public class MeetingUnPayOrderTimeOutTask implements TimeOutTaskHandleTask {


    @Resource
    private IMeetingOrderInfoService meetingOrderInfoService;

    @Override
    public void cancel(String rediskey) {
        // note 默认一次取20个
        Set<ZSetOperations.TypedTuple<String>> items = TaskTimeOutUtil.acquireTimeoutTask(rediskey, 0, 20);
        if (items == null || items.isEmpty()) {
            return;
        }

        items.stream().iterator().forEachRemaining(item -> {
            long score = item.getScore().longValue();
            long nowSecond = TaskTimeOutUtil.currentSeconds();
            if (nowSecond >= score) {
                String orderId = item.getValue();
                Long num = TaskTimeOutUtil.dequeue(rediskey, orderId);
                if (num != null && num > 0) {
                    // TODO 实际业务逻辑
                    meetingOrderInfoService.updateCancelUnpayOrder(orderId);
                    log.info("订单ID为:{}的订单已超时取消", orderId);
                }
            }
        });
    }
}
